﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using DMS.Business.Modules.ArchivesManagement;
using DMS.Business.Utility;
using DMS.Data;

namespace DMS.Web.Modules.ArchivesManagement
{
    public partial class ArchInfoList : System.Web.UI.UserControl
    {
        public string BaseInfoId { get; set; }

        public static string SortExpressionStore { get; set; }

        public static string SortDirectionStore { get; set; }

        private IQueryable<AM_ArchivesInfo> ArchInfos { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitControls();
                Search();
            }
        }

        private void InitControls()
        {
            if (!SystemContext.Current.LoginUser.IsInRole("档案管理员;系统管理员;"))
            {
                this.uploadBtn.Visible = false;
                this.addBtn.Visible = false;
                this.destoryBtn.Visible = false;

                archInfoList.Columns[12].Visible = false;
            }
        }

        protected string GetCondition()
        {
            string condition = "";

            condition += string.Format(" and it.BaseInfoID='{0}'", BaseInfoId);

            if(ddlBelongYear.SelectedValue!="")
            {
                condition += string.Format(" and it.BelongYear = '{0}'", ddlBelongYear.SelectedValue);
            }
            if(ddlBelongMonth.SelectedValue!="")
            {
                condition += string.Format(" and it.BelongMonth = '{0}'", ddlBelongMonth.SelectedValue);
            }
            if (txtName.Text != "")
            {
                condition += string.Format(" and it.Name like '%{0}%'", txtName.Text.Trim());
            }
            if (txtType.SelectedValue != "")
            {
                condition += string.Format(" and it.Type = '{0}'", txtType.SelectedValue);
            }
            if (txtInitDateBegin.Text != "")
            {
                condition += string.Format(" and it.InitDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtInitDateBegin.Text));
            }
            if (txtInitDateEnd.Text != "")
            {
                condition += string.Format(" and it.InitDate <= cast('{0}' as System.DateTime)", DateTime.Parse(txtInitDateEnd.Text));
            }
            if (txtBeginTimeBegin.Text != "")
            {
                condition += string.Format(" and it.CustodyBeginDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtBeginTimeBegin.Text));
            }
            if (txtBeginTimeEnd.Text != "")
            {
                condition += string.Format(" and it.CustodyBeginDate <= cast('{0}' as System.DateTime)", DateTime.Parse(txtBeginTimeEnd.Text));
            }
            if (txtExpireTimeBegin.Text != "")
            {
                condition += string.Format(" and it.CustodyEndDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtExpireTimeBegin.Text));
            }
            if (txtExpireTimeEnd.Text != "")
            {
                condition += string.Format(" and it.CustodyEndDate <= cast('{0}' as System.DateTime)", DateTime.Parse(txtExpireTimeEnd.Text));
            }
            if (txtPersonName.Text != "")
            {
                condition += string.Format(" and it.PersonName like '%{0}%'", txtPersonName.Text.Trim());
            }
            if (ddlDestroy.SelectedValue != "")
            {
                condition += string.Format(" and it.IsDestroy = {0}", ddlDestroy.SelectedValue);
            }
            if (ddlIsExpire.SelectedValue != "")
            {
                if(ddlIsExpire.SelectedValue=="True")
                {
                    condition += string.Format(" and it.CustodyEndDate <= cast('{0}' as System.DateTime)", DateTime.Now);
                }else
                {
                    condition += string.Format(" and (it.CustodyEndDate > cast('{0}' as System.DateTime) or it.CustodyYear=0 )", DateTime.Now);
                }
            }

            return condition;
        }

        private void Search()
        {
            int total;
            string condition = GetCondition();

            if (this.PageSize.Text == "")
                this.PageSize.Text = "15";
            pager.PageSize = int.Parse(this.PageSize.Text);
            List<AM_ArchivesInfo> list = ArchInfoService.GetArchInfos(SystemContext.Current.LoginAuthUser, condition,
                                                                      pager.CurrentPageIndex, pager.PageSize, out total);

            // 获取GridView排序数据列及排序方向
            string sortExpression = "";
            string sortDirection = "";
            if (string.IsNullOrEmpty(SortExpressionStore))
            {
                sortExpression = this.archInfoList.Attributes["SortExpression"];
                sortDirection = this.archInfoList.Attributes["SortDirection"];

                SortExpressionStore = sortExpression;
                SortDirectionStore = sortDirection;
            }
            else if (SortExpressionStore != this.archInfoList.Attributes["SortExpression"] ||
                     SortDirectionStore != this.archInfoList.Attributes["SortDirection"])
            {
                sortExpression = this.archInfoList.Attributes["SortExpression"];
                sortDirection = this.archInfoList.Attributes["SortDirection"];

                SortExpressionStore = sortExpression;
                SortDirectionStore = sortDirection;
            }else
            {
               sortExpression = SortExpressionStore ;
               sortDirection = SortDirectionStore ;
            }



            IQueryable<AM_ArchivesInfo> queryableList;
            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                //调用排序方法对当前页数据进行排序
                queryableList = (list.AsQueryable()).OrderUsingSortExpression(sortExpression + " " + sortDirection);
            }
            else
            {
                queryableList = list.AsQueryable();
            }

            ArchInfos = queryableList;

            // GridView绑定并显示数据
            this.archInfoList.DataSource = queryableList;
            this.archInfoList.DataBind();

            pager.RecordCount = total;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pager_PageChanged(object sender, EventArgs e)
        {
            Search();
        }

        protected void DealCommand(object sender, GridViewCommandEventArgs e)
        {
            string commandName = e.CommandName;
            var id = e.CommandArgument as string;
            if (commandName.Equals("DeleteArchInfo"))
            {
                ArchInfoService.DeleteArchInfo(id);
            }
            Search();
        }

        //列表的排序事件
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();
            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == archInfoList.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (archInfoList.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            archInfoList.Attributes["SortExpression"] = sortExpression;
            archInfoList.Attributes["SortDirection"] = sortDirection;
            
            Search();
        }

        protected void ExportClick(object sender, EventArgs e)
        {
            string condition = GetCondition();

            Dictionary<string, DataTable[]> forms = new Dictionary<string, DataTable[]>();
            List<DataTable> tables = ArchInfoService.GetArchInfoTable(SystemContext.Current.LoginAuthUser, condition);
            
            if(tables==null)
            {
                ClientHelper.Instance.Alert("导出记录数超过Excel的最大行数（65535），请先筛选数据，分多次导出，谢谢。");
                return;
            }

            forms.Add("档案资料信息", tables.ToArray());
            try
            {
                ClientHelper.Instance.ExportToExcel(forms, "档案资料信息");
            }catch(Exception ex)
            {
                LogHelper.LogException(ex);
            }
            
        }
    }
}